<?php

namespace app\wechat\service;

use app\admin\service\BaseService;
use app\wechat\model\OfficeUserModel;
use think\facade\Db;

class OfficeUserService extends BaseService
{
    /**
     * 获取微信授权用户信息
     *
     * @Author tanruizheng
     * @DateTime 2021-08-10
     * @param [type] $appid
     * @return void
     */
    public static function ouathUser($appid){
        $office = new OfficeService($appid);
        // 获取 OAuth 授权结果用户信息
        $user = $office->getApp()->oauth->user();
        // 原始API返回的结果
        $original = $user->getOriginal();
        Db::startTrans();
        try {
            //微信微信公众号用户信息
            $officeUserModel = OfficeUserModel::where('open_id',$original['openid'])->findOrEmpty();
            $officeUserModel->app_id = $appid;
            $officeUserModel->open_id = $original['openid'];
            $officeUserModel->nick_name = $original['nickname'];
            $officeUserModel->sex = $original['sex'];
            $officeUserModel->language = $original['language'];
            $officeUserModel->city = $original['city'];
            $officeUserModel->province = $original['province'];
            $officeUserModel->country = $original['country'];
            $officeUserModel->avatar_url = $original['headimgurl'];
            $officeUserModel->union_id = isset($original['union_id']) ? $original['union_id'] : '';
            $officeUserModel->save();
            //生成Token信息
            $authTokenService = new AuthTokenService();
            $code = $authTokenService->createAuthToken($appid,$original['openid']);
            Db::commit();
            return self::createSuccess('success',[
                'code' => $code,
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            return self::createFail($e->getMessage());
        }
    }
}